package com.qian.apiserver.tio;

import com.qian.apiserver.tio.common.HelloPacket;
import com.qian.apiserver.tio.handler.GameTioHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.tio.client.AioClient;
import org.tio.client.ClientChannelContext;
import org.tio.client.ClientGroupContext;
import org.tio.client.ReconnConf;
import org.tio.client.intf.ClientAioHandler;
import org.tio.client.intf.ClientAioListener;
import org.tio.core.Aio;
import org.tio.core.Node;

import javax.annotation.PostConstruct;

@Component
public class TioStartHandler  {
    @Value("${game.server.address:}")
    private String HOST;
    @Value("${game.server.port:}")
    private Integer PORT;
    //服务器节点
    public static Node serverNode;

    //handler, 包括编码、解码、消息处理
    public static ClientAioHandler aioClientHandler;

    //事件监听器，可以为null，但建议自己实现该接口，可以参考showcase了解些接口
    public static ClientAioListener aioListener = null;

    //断链后自动连接的，不想自动连接请设为null
    private static ReconnConf reconnConf = new ReconnConf(5000L);

    //一组连接共用的上下文对象
    public static ClientGroupContext clientGroupContext = new ClientGroupContext(aioClientHandler, aioListener, reconnConf);

    public static AioClient aioClient = null;
    public static ClientChannelContext clientChannelContext = null;
    @PostConstruct
    public void init(){
        serverNode = new Node(HOST,PORT);
        aioClientHandler = new GameTioHandler();
    }

    /**
     * 启动程序入口
     */


    public void send(String jsonData) throws Exception {
        clientGroupContext.setHeartbeatTimeout(30000);
        aioClient = new AioClient(clientGroupContext);
        clientChannelContext = aioClient.connect(serverNode);
        HelloPacket packet = new HelloPacket();
        packet.setBody(jsonData.getBytes(HelloPacket.CHARSET));
        Aio.send(clientChannelContext, packet);
    }
}
